<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: blue;
            position: absolute;
            left: 500px;
            top: 0px;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        // 点击box1的时候 box1 开始运动 
        var box1Ele = document.querySelector(".box1");
        var box2Ele = document.querySelector(".box2");
        var num = 1;
        box1Ele.onclick = function(){
            // console.log("点击了box1");
          var timer =   setInterval(function(){
                // 让box1 从左至右运动 ；
                // 获取元素当前的left的位置 
               
                // 在方块运动的时候检测是否和 蓝色的方块碰撞了；
                // console.log(isCrash(box1Ele,box2Ele));
                var leftNum = parseInt( getComputedStyle(box1Ele)['left']);
                if(isCrash(box1Ele,box2Ele)){
                    num *= -1 ;
                }
                leftNum += num;
                if(leftNum<0){
                    clearInterval(timer);
                }

                box1Ele.style.left = leftNum + "px";

            }, 1);
        }




        function isCrash(box1Ele, box2Ele) {
            // 检测 box1 和box2 在x轴上是否碰撞了；
            var minAx = box1Ele.offsetLeft;
            var maxAx = box1Ele.offsetLeft + box1Ele.offsetWidth;

            var minAy = box1Ele.offsetTop;
            var maxAy = box1Ele.offsetTop + box1Ele.offsetHeight;


            var minBx = box2Ele.offsetLeft;
            var maxBx = box2Ele.offsetLeft + box2Ele.offsetWidth;

            var minBy = box2Ele.offsetTop;
            var maxBy = box2Ele.offsetTop + box2Ele.offsetHeight;

            if (maxAx >= minBx && minAx <= maxBx && maxAy >= minBy && minAy <= maxBy) {
                // console.log("碰撞了");
                return true;
            }else{
                return false;
            }
        }

    </script>
</body>
</html>